
const objStr = (apiUrl, params = {}) => {
    if (JSON.stringify(params) === '{}') { return apiUrl; }
    const str = JSON.stringify(params).replace(/,/g, '&')
    const urlData = str.substring(1, str.length - 1).replace(/:/g, '=')
    const urlStr = urlData.replace(/"/g, '').trim()
    return `${apiUrl}?${urlStr}`
}

const requestApi = (apiUrl, data, { method, hideLoading = false,hideMessage = false ,ip='ZR'}, params) => {
  if (!hideLoading) {
    uni.showLoading({
      title: '加载中...',
      mask: true
    });
  }
  return new Promise((resolve, reject)=>{
    let ipUrl=''
    if(ip==='ZR'){
      ipUrl = process.uniEnv.commonPMS20
    }else if(ip === 'JN'){
      ipUrl = process.uniEnv.BASE_JN
    }else{
      console.log('阻断修复')
    }
    // const ip = process.uniEnv.commonPMS20
    uni.request({
      url: ipUrl + objStr(apiUrl, params),
      method,
      dataType: 'json',
      timeout: 10000 * 60,
      header: {
        // 'pmsToken': uni.getStorageSync('pmsToken'),
        // 'pmsToken': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI0Mjc0NyIsImV4cCI6MTcwNDcxMzg4MywidXNlck5hbWUiOiLlhazno4oiLCJpYXQiOjE3MDQ2Nzc4ODN9.wZR-GErNA8XCbU_9_tISpKGig1TiYb9H3voaz01vJZE',
          /*
          * 从缓存中获取到当前的token值
          * */
          "sysToken": uni.getStorageSync("sysToken"),
        // "sysToken": 'c64dd4dac160904f76a09c81b078228a',
      },
        /*
        * data为传参数据
        * */
      data,
      success: (res) => {
        // 需要端口号
        uni.setStorageSync('urlDownload', res.header['access-control-allow-origin'])
        /*
        * 获取数据成功之后，停止下拉刷新操作
        * */
        uni.stopPullDownRefresh();
        uni.hideLoading();
        if (+res.data.code === 200) {
          return resolve(res.data)
        }
        if (!hideMessage) {
          uni.showModal({
            title: "温馨提示",
            content: res.data.message || "请求异常",
            confirmColor: '#eb4b4b',
            showCancel: false
          });
          return reject(res.data)
        }
        return reject(res.data)

      },
      fail: err => {
        uni.showModal({
            title: "温馨提示",
            content: "请求超时，请稍后再试",
            confirmColor:'#eb4b4b',
            showCancel: false
        });
        uni.hideLoading();
        uni.stopPullDownRefresh();
        return reject(err)
      }
    });
  })
}
export default {
  get(url, data = {}, options = {}){
    return requestApi(url, data, { method:'GET', ...options })
  },
  post(url, data = {}, options = {}, params = {}){
    return requestApi(url, data, { method:'POST', ...options }, params)
  }
}
